package com.ld.hpfs.web.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.dao.UtilMapper;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.EnterInvoiceService;
import com.ld.hpfs.service.InvoiceBuyService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class InvoiceBuyController {
	private static final Logger logger = LoggerFactory
			.getLogger(InvoiceBuyController.class);

	@Autowired
	private InvoiceBuyService invoicebuyservice;
	@Autowired
    private UtilMapper          utilMapper;
	@Autowired
	private EnterInvoiceService enterInvoiceService;
	
	/**
	 * 得到发票购入一览信息
	 */
	@RequestMapping(value = "/getInvoiceBuyList")
	public void getTableNameList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {

		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");

		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			// 发票类型
			String invoiceType = request.getParameter("invoiceType");
			// 开始日期
			String buysdate = request.getParameter("buysdate");
			// 结束日期
			String buyedate = request.getParameter("buyedate");
			String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
			if (user != null) {
				param.put("pageEnd", page.getStart() + page.getLimit());
				param.put("pageStart", page.getStart());
				param.put("invoiceType", invoiceType);
				param.put("buysdate", buysdate);
				param.put("buyedate", buyedate);
				param.put("companyId", companyId);
				param.put("lang", lang);
				ArrayList<HashMap<String, Object>> logs = invoicebuyservice.getInvoiceBuyList(param);
				if (logs != null && logs.size() > 0) {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 新建保存和修改保存
	 */
	@RequestMapping(value = "/saveInvoiceBuy")
	public void saveInvoiceBuy(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		try {
			if (user != null){
				HashMap<String, Object> param = new HashMap<String, Object>();
				HashMap<String, Object> result = new HashMap<String, Object>();
				String userId = user.getUserId().toString();
				String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
				
				String invoiceBuyId = request.getParameter("invoiceBuyId");
				String invoiceBuyCode = request.getParameter("invoiceBuyCode");
				String invoiceBuySno = request.getParameter("invoiceBuySno");
				String invoiceBuyEno = request.getParameter("invoiceBuyEno");
				String invoiceBuyType = request.getParameter("invoiceBuyType");
				String invoiceBuyDate = request.getParameter("invoiceBuyDate");
				String invoiceMach = request.getParameter("invoiceMach");
				String invoiceBuyRemark = request.getParameter("invoiceBuyRemark");
				
				param.put("userId", userId);
				param.put("companyId", companyId);
				param.put("invoiceBuyCode", invoiceBuyCode);
				param.put("invoiceBuySno", invoiceBuySno);
				param.put("invoiceBuyEno", invoiceBuyEno);
				param.put("invoiceBuyType", invoiceBuyType);
				param.put("invoiceBuyDate", invoiceBuyDate);
				param.put("invoiceMach", invoiceMach);
				param.put("invoiceBuyRemark", invoiceBuyRemark);
				
				int ret = 0;
				// 如果id不为空说明是编辑操作
				if (!Tools.isEmpty(invoiceBuyId)) {
					param.put("invoiceBuyId", invoiceBuyId);
					try {
						ret = invoicebuyservice.editInvoiceBuy(param);
					} catch (Exception e) {
						System.out.println(e);
						ret = -1;
					}
				} else {
					try {
						ret = invoicebuyservice.saveInvoiceBuy(param);
					} catch (Exception e) {
						System.out.println(e);
						ret = -1;
					}
				}
				if (ret == 0) {
					result.put("resultcode", 0);
				} else {
					result.put("resultcode", 9);
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	// 获取税控器下拉框信息
	@RequestMapping(value = "/getMachInfo")
	public void getMachInfo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");

		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			param.put("companyId", companyId);
			ArrayList<HashMap<String, Object>> result = invoicebuyservice.getMachInfo(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	// 删除一览数据
	@RequestMapping(value = "/deleteInvoiceList")
	public void deleteInvoiceList(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		
		String docentry = (String) request.getParameter("docentry");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		String[] docentrylist = docentry.split(",");
		try {
			List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			for (int i = 0; i < docentrylist.length; i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("docentry", docentrylist[i]);
				list.add(map);
			}
			param.put("docentry", list);
			int ret = 0;
			try {
				ret = invoicebuyservice.deleteInvoiceList(param);
			} catch (Exception e) {
				System.out.println(e);
				ret = -1;
			}
			if (ret == 0) {
				result.put("resultcode", 0);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	@RequestMapping(value = "/getInvoiceDataForEdit", method = RequestMethod.POST)
	public void getInvoiceDataForEdit(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		// 报告id
		String docentry = (String) request.getParameter("docentry");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");

		try {
			param.put("docentry", docentry);

			ArrayList<HashMap<String, Object>> logs = invoicebuyservice.getInvoiceDataForEdit(param);
			int count = logs.size();
			String code = null;
			String sno = null;
			String eno = null;
			String type = null;
			String date = null;
			int mach = 0;
			String remark = null;
			if (count == 1) {
				code = logs.get(0).get("code").toString();
				sno = logs.get(0).get("sno").toString();
				eno = logs.get(0).get("eno").toString();
				type = logs.get(0).get("type").toString();
				date = logs.get(0).get("date").toString();
				mach = Integer.parseInt(logs.get(0).get("mach").toString());
				remark = logs.get(0).get("remark").toString();
			}
			result.put("code", code);
			result.put("sno", sno);
			result.put("eno", eno);
			result.put("type", type);
			result.put("date", date);
			result.put("mach", mach);
			result.put("remark", remark);
			
			result.put("count", count);
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	// 获取税控器下拉框信息
	@RequestMapping(value = "/getInvoiceBuyType")
	public void getInvoiceBuyType(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");

		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
			int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(companyId));
			String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
			param.put("language", language);
			param.put("groupId", groupId);
			ArrayList<HashMap<String, Object>> result = enterInvoiceService.getInvoiceType(param);
			HashMap<String, Object> type = new HashMap<String, Object>();
			if (language.equals("en")) {
				type.put("text", "All");
			} else {
				type.put("text", "全部");
			}
			type.put("value", "0");
			result.add(0, type);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
}